import io from 'socket.io-client';
import { WEBSOCKETURL } from './constants';

let socket;
let IsSubscribeUserOrder = false; // 是否订阅了 loginTrade
let _userInfo = {userNameChain: ''};  // 暂存的用户信息，关闭socket的时候，从这里拿数据

/**
 * 在首次订阅时，可能用户还未登录
 * 用户登录后，如果 存在 socket 则在原来的 socket 上进行 emit
 * @param {Object} userInfo {userNameChain}
 * @param {Function} cb 回调函数 (err, type: 返回数据类型, data: 返回的数据)
 */
function subscribeCoinxpMarket(userInfo, cb?: (err: Error | null, type: string, data: any) => void) {

    try {
        if (!socket) {

            socket = io(WEBSOCKETURL, {
                transports: ['websocket'],
            });

            socket.on('connect', function () {
                socket.emit('subscribeMarket', 1000);
                subscribeCoinxpUserOrder(userInfo);
            });

            socket.on('userTrades', (userTrades) => {
                cb && cb(null, 'userTrades', userTrades);
            });

            socket.on('coinxpMarketInfo', coinxpMarket => {
                cb &&  cb(null, 'coinxpMarketInfo', coinxpMarket);
            });

            socket.on('disconnect', function () {
                console.log('websocket disconnect .... ');
            });

            socket.on('error', function(e) {
                console.error('socket error...', e)
            })
        }
    } catch (e) {
        console.error('subscribeCoinxpMarket.... e...' + e);
    }
}

// 订阅 用户的委托记录
function subscribeCoinxpUserOrder(userInfo) {
    if (userInfo && userInfo.userNameChain && ! IsSubscribeUserOrder) {
        _userInfo = userInfo;
        IsSubscribeUserOrder = true;
        console.warn('subscribeCoinxpMarket...emit loginTrade.....')
        if (socket) {
            socket.emit('loginTrade', { usernameChain: userInfo.userNameChain });
        }
    }
}

// 取消订阅 用户的委托记录
function emitLogoutTrade () {
    console.log('emitLogoutTrade?', IsSubscribeUserOrder, _userInfo);
    if (IsSubscribeUserOrder && _userInfo && _userInfo.userNameChain) {
        socket.emit('logoutTrade', { usernameChain: _userInfo.userNameChain });
        console.log('emitLogoutTrade......', _userInfo);
        _userInfo = {userNameChain: ''};
        IsSubscribeUserOrder = false;
    }
}

// 关闭 socket
function closeCoinxpMarket(userInfo) {
    if (userInfo && userInfo.userNameChain) {
        socket.emit('logoutTrade', { usernameChain: userInfo.userNameChain });
    }
    IsSubscribeUserOrder = false;
    socket.close();
    socket = null;
    console.log('close Socket', userInfo);
    console.log('websocket closed', socket);
}

export {
    subscribeCoinxpMarket,
    closeCoinxpMarket,
    emitLogoutTrade,
    subscribeCoinxpUserOrder
}

